<?php

namespace business\elasticsearch\services;

use business\elasticsearch\models\SupplierModel;

class IndustryService
{

    public function getIndustryData($params = [])
    {
        $list_condition = $this->generateQueryCondition($params);
        $fields = ['supplierId', 'companyName', 'regCapital', 'regLocationCity','basicCategoryCode3',
                    'projectCount','provinceCode','cityCode','provinceName','cityName','hundredCount'];
        $query = SupplierModel::find()->source($fields)->query($list_condition);

        $total = $query->count();  //总数
        $result = ['resultNum' => $total, 'resultList' => [], 'resultAggregationSupplier' => [],
            'developerCooperationCount' => [], 'ycSupplierCount' => 0
        ];
        if($total > 0){
            $data = $query->orderBy(['hundredCount' => SORT_DESC, 'projectCount' => SORT_DESC])
                ->offset(($params['page'] - 1) * $params['pageSize'])->limit($params['pageSize'])
                ->asArray()->all();
            $result['resultList'] = array_column($data, '_source');   //供应商列表数据
        }

        //获取百强战略供应商
        $condition = $this->generateQueryCondition($params);
        if ($params['cooperation']!=2) {
            $condition['bool']['filter'][] = ['range' => ['hundredCount' => ['gt' => 0]]];
        }
        $result['ycSupplierCount'] = SupplierModel::find()->query($condition)->count();  //百强战略合作单位供应商数量

        $groupData = $this->getAggregationSupplierData($params['areaCode']);
//        var_dump($groupData);exit;

        $result['resultAggregationSupplier'] = !empty($groupData['aggregations']['group_by_area']['buckets']) ?
                                            $groupData['aggregations']['group_by_area']['buckets'] : [];  //供应商分布数据
        //获取开发商合作单位数量
        $cooperation_condition = $list_condition;
        $filter = [
            ['range' =>
                ['projectCount' => ['gt' => 0]],
            ],
            ['range' =>
                ['hundredCount' => ['gt' => 0]],
            ]
        ];
        $cooperation_condition['bool']['filter'][] = ['bool' => ['should' => $filter]];
        $cooperationData = $this->getAggregationCooperationSupplierData($cooperation_condition);
        $result['developerCooperationCount'] = !empty($cooperationData['hits']['total']) ?
                                                $cooperationData['hits']['total'] : 0;  //开发商合作单位的供应商数量
//echo json_encode($condition);exit;

//        $this->getAggregationHundredSupplierData();

        if(!empty($result['_shards'])){
            \Yii::info('aggregation data use shards，total：' . $result['_shards']['total'] .
                '，successful：' . $result['_shards']['successful'] . '，failed：' . $result['_shards']['failed']);
        }

//        var_dump($result);exit;
        return $result;

    }

    /**
     * 生成查询条件
     * @param array $params
     * @return array
     * @throws \Exception
     */
    private function generateQueryCondition($params = [])
    {
        if(empty($params['categoryCode'])){
            throw new \Exception("服务分类必填");
        }

        $condition = [];
        $categoryCode = explode(",", $params['categoryCode']);
        if(is_array($categoryCode)){ //所属行业
            $condition['bool']['filter'][] = ['terms' => ['basicCategoryCode3' => $categoryCode]];
        }else{
            $condition['bool']['filter'][] = ['term' => ['basicCategoryCode3' => $categoryCode]];
        }

        if(!empty($params['areaCode']) && $params['areaCode'] != 'china'){ //所在地区（除了全国）
            $areaCode = explode(',', $params['areaCode']);
            $condition['bool']['filter'][] = ['terms' => ['provinceCode.keyword' => $areaCode]];
        }


        if($params['cooperation'] == 1){ //开发商合作单位
            $filter = [
                ['range' =>
                    ['projectCount' => ['gt' => 0]],
                ],
                ['range' =>
                    ['hundredCount' => ['gt' => 0]],
                ]
            ];
            $condition['bool']['filter'][] = ['bool' => ['should' => $filter]];
        }
        if($params['cooperation'] == 2){ //百强战略合作单位
            $condition['bool']['filter'][] = ['range' => ['hundredCount' => ['gt' => 0]]];
        }

        $register_cap = [];
        if (!empty($params['beginRegCapital'])) {
            $register_cap['gte'] =  $params['beginRegCapital'];
        }
        if (!empty($params['endRegCapital'])&&$params['endRegCapital']!='all') {
            $register_cap['lte'] =  $params['endRegCapital'];
        }
        if(count($register_cap)){
            $condition['bool']['filter'][] = ['range' => ['regCapital' => $register_cap]];
        }


        return $condition;

    }

    /**
     * 获取聚合后的供应商分布
     * @param $areaCodes
     * @return array|mixed
     */
    private function getAggregationSupplierData($areaCodes = '')
    {
        $groupData = [];
        if(!empty($areaCodes) && $areaCodes == 'china'){ //选中全国
            $aggregation = [
                'group_by_area' => [
                    'terms' => ['field' => 'provinceName.keyword'],
                ],
            ];
            $search = [
                'size' => 0,
                'aggs' => $aggregation,
            ];
            $query = SupplierModel::find()->createCommand();
            $query->queryParts = $search;
            $groupData = $query->search();
        }else if(!empty($areaCodes) && $areaCodes != 'china'){ //选中省份
            $aggregation = [
                'group_by_area' => [
                    'terms' => ['field' => 'cityName.keyword'],
                ],
            ];

            $areaCode = explode(',', $areaCodes);
            $query = [
                'constant_score' => [
                    "filter" => [
                        "terms" => [
                            "provinceCode.keyword" => $areaCode,
                        ]
                    ],
                ],
            ];

            $search = [
                'size' => 0,
                'query' => $query,
                'aggs' => $aggregation,
            ];
            $query = SupplierModel::find()->createCommand();
            $query->queryParts = $search;
            $groupData = $query->search();
        }

        return $groupData;
    }

    /**
     * 开发商合作单位的供应商数量
     * @param array $condition
     * @return mixed
     */
    private function getAggregationCooperationSupplierData($condition = 0)
    {
//        if($cooperation == 2){ //百强战略合作单位
//            $query = [
//                'constant_score' => [
//                    "filter" => [
//                        'range' => [
//                            'hundredCount' => ['gt' => 0]
//                        ],
//                    ],
//                ]
//            ];
//        }else{ //开发商合作单位或者不限
//            $filter = [
//                ['range' =>
//                    ['projectCount' => ['gt' => 0]],
//                ],
//                ['range' =>
//                    ['hundredCount' => ['gt' => 0]],
//                ]
//            ];
//            $query = ['bool' => ['should' => $filter]];
//        }
//
//        $aggregation = [
//            'group_by_supplierId' => [
//                'terms' => ['field' => 'supplierId.keyword'],
//            ],
//        ];
//
//        $search = [
//            'size' => 0,
//            'query' => $query,
//            'aggs' => $aggregation,
//        ];
//
//        $query = SupplierModel::find()->createCommand();
//        $query->queryParts = $search;
//        $cooperationData = $query->search();
        $query = $condition;

        $aggregation = [
            'group_by_supplierId' => [
                'terms' => ['field' => 'supplierId.keyword'],
            ],
        ];

        $search = [
            'size' => 0,
            'query' => $query,
            'aggs' => $aggregation,
        ];

        $query = SupplierModel::find()->createCommand();
        $query->queryParts = $search;
        $cooperationData = $query->search();

        return $cooperationData;
    }

}